package cn.itcast.dao.impl;

import cn.itcast.dao.ItemsDao;
import cn.itcast.domain.Items;
import cn.itcast.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ItemsDaoImpl implements ItemsDao {
    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;

    //查询所有商品信息
    public List<Items> findAll() {
        List<Items> lis = new ArrayList<Items>();
        try {
            //1.获取连接
            conn = JDBCUtil.getConn();
            //2.编写sql,并创建预编译对象
            String sql = "select * from items";
            ps = conn.prepareStatement(sql);

            //获取结果集,并遍历
            rs = ps.executeQuery();
            while (rs.next()){
                Items it = new Items(rs.getInt(1),rs.getString(2),rs.getFloat(3),rs.getString(4));
                lis.add(it);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            JDBCUtil.close(conn,ps,rs);
        }
        return lis;
    }
    //添加商品
    public void add(Items it) {

        try {
            //1.获取连接
            conn = JDBCUtil.getConn();
            //2.编写sql,并创建预编译对象
            String sql = "insert into items values(?,?,?,?)";
            ps = conn.prepareStatement(sql);
            //2.1添加数据,并执行
            ps.setInt(1,it.getId());
            ps.setString(2,it.getIname());
            ps.setFloat(3,it.getPrice());
            ps.setString(4,it.getAddress());
            ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            JDBCUtil.close(conn,ps);
        }

    }
}
